package manager.modulo.ferramenta.fonte;

import java.sql.SQLException;
import java.util.LinkedList;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import manager.auxiliares.*;
import manager.helpers.validation.FormatedFieldValidator;
import manager.helpers.validation.TextFieldValidator;
import manager.helpers.validation.ValidationFunctions;
import manager.modulo.ferramenta.dao.FerramentaDao;
import manager.modulo.ferramenta.enumerator.EnumSituacaoFerramenta;
import manager.modulo.ferramenta.enumerator.EnumSituacaoFerramenta.SituacaoFerramenta;
import manager.modulo.funcionario.dao.FuncionarioDao;
import manager.principal.fonte.JanelaLogin;

/**
 *
 * @author Thiago
 */
public class JanelaFerramenta extends javax.swing.JFrame {

    int idFerramenta = 0;

    /**
     * Creates new form UserWindow
     */
    public JanelaFerramenta(int newIdPartner) {
        try {
            // Define layout de acordo com o SO que estiver rodando
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            this.setIconImage(JanelaLogin.icon);
            initComponents();
            idFerramenta = newIdPartner;
            configurarJanela();
            this.setLocationRelativeTo(null);
            this.setVisible(true);

        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, "Funcionários");
        }
    }

    private void configurarCamposObrigatorios() {
        ((TextFieldValidator) jTextField5).validarCampo();//Nome
        ((TextFieldValidator) jTextField12).validarCampo();//Pai
        ((FormatedFieldValidator) jFormattedTextField3).validarCampo();//Valor
        ((FormatedFieldValidator) jFormattedTextField5).validarCampo();//Data de Nascimento
        ((TextFieldValidator) jTextField1).validarCampo();//Fabricante
        ((TextFieldValidator) jTextField2).validarCampo();//Modelo
        ((TextFieldValidator) jTextField7).validarCampo();//Localizacao
    }

    private LinkedList<String> validarCampos() {
        LinkedList<String> fieldList = new LinkedList<String>();
        if (!((TextFieldValidator) jTextField12).validarCampo()) {//Nome
            fieldList.add(((TextFieldValidator) jTextField12).getjLabel().getText());
        }
        if (!((TextFieldValidator) jTextField5).validarCampo()) {//Identificador
            fieldList.add(((TextFieldValidator) jTextField5).getjLabel().getText());
        }
        if (!((FormatedFieldValidator) jFormattedTextField3).validarCampo()) {//Valor
            fieldList.add(((FormatedFieldValidator) jFormattedTextField3).getjLabel().getText());
        }
        if (!((FormatedFieldValidator) jFormattedTextField5).validarCampo()) {//Data de Compra
            fieldList.add(((FormatedFieldValidator) jFormattedTextField5).getjLabel().getText());
        }
        if (!((TextFieldValidator) jTextField1).validarCampo()) {//Fabricante
            fieldList.add(((TextFieldValidator) jTextField1).getjLabel().getText());
        }
        if (!((TextFieldValidator) jTextField2).validarCampo()) {//Modelo
            fieldList.add(((TextFieldValidator) jTextField2).getjLabel().getText());
        }
        if (!((TextFieldValidator) jTextField7).validarCampo()) {//Localização
            fieldList.add(((TextFieldValidator) jTextField7).getjLabel().getText());
        }
        return fieldList;
    }

    private void carregarInformacoes() {
        jButton1.setText("Editar");
        jButton1.setIcon(new Icons().getEdit());

        FerramentaDao ferramentaDao = new FerramentaDao();
        ferramentaDao.buscar(idFerramenta);

        jTextField5.setText(ferramentaDao.getIdentificador());//Identificador
        jTextField12.setText(ferramentaDao.getNome());//Nome
        jFormattedTextField3.setValue(ferramentaDao.getValor() / 100);
        jFormattedTextField5.setText(Format.formatarTimeStampApresentacao(ferramentaDao.getDtCompra()));
        jTextField1.setText(ferramentaDao.getFabricante());
        jTextField2.setText(ferramentaDao.getModelo());
        jComboBox6.setSelectedItem(EnumSituacaoFerramenta.ConvertEnumString(ferramentaDao.getSituacao()));
        jTextArea1.setText(ferramentaDao.getDescricao());
        jTextField7.setText(ferramentaDao.getLocalizacao());

        if (ferramentaDao.getIdFuncionario() != 0) {
            FuncionarioDao funcionarioDao = new FuncionarioDao();
            funcionarioDao.buscar(ferramentaDao.getIdFuncionario());
            jTextField6.setText(funcionarioDao.getIdentificador());
        }

    }

    private FerramentaDao configurarFerramentaDao(boolean editar) {
        FerramentaDao ferramentaDao = new FerramentaDao();
        if (editar) {
            ferramentaDao.buscar(idFerramenta);
        }
        ferramentaDao.setIdentificador(jTextField5.getText());
        ferramentaDao.setNome(jTextField12.getText());
        ferramentaDao.setValor((int) (((Number) jFormattedTextField3.getValue()).doubleValue() * 100));
        ferramentaDao.setDtCompra(Format.formatVisualDateToTimestamp(jFormattedTextField5.getText()));
        ferramentaDao.setFabricante(jTextField1.getText());
        ferramentaDao.setModelo(jTextField2.getText());
        ferramentaDao.setSituacao(EnumSituacaoFerramenta.ConvertStringEnum(jComboBox6.getSelectedItem().toString()));
        ferramentaDao.setDescricao(jTextArea1.getText());
        ferramentaDao.setLocalizacao(jTextField7.getText());
        return ferramentaDao;
    }

    private void adicionarFerramenta() {
        try {
            if (FerramentaDao.getIdFerramentaPorIdentificador(jTextField5.getText()) == 0) {
                try {
                    JanelaLogin.connection.setAutoCommit(false);

                    FerramentaDao ferramentaDao = configurarFerramentaDao(false);

                    ferramentaDao.inserir();

                    JanelaLogin.connection.commit();

                    JOptionPane.showMessageDialog(null, "Ferramenta cadastrada com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                    this.dispose();
                } catch (Exception e) {
                    JanelaLogin.connection.rollback();
                    MensagemExcessao.mostrarMensagem(e, "Inserção de Ferramentas");
                } finally {
                    JanelaLogin.connection.setAutoCommit(true);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Esta Ferramenta já esta cadastrada.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, "Inserção de Ferramentas");
        }
    }

    private void editarFerramenta() {
        try {
            if ((FerramentaDao.getIdFerramentaPorIdentificador(jTextField5.getText()) == 0) || (FerramentaDao.getIdFerramentaPorIdentificador(jTextField5.getText()) == idFerramenta)) {
                try {
                    JanelaLogin.connection.setAutoCommit(false);

                    FerramentaDao ferramentaDao = configurarFerramentaDao(true);
                    ferramentaDao.atualizar();

                    JanelaLogin.connection.commit();

                    JOptionPane.showMessageDialog(null, "Ferramenta atualizada com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                    this.dispose();
                } catch (Exception e) {
                    JanelaLogin.connection.rollback();
                    MensagemExcessao.mostrarMensagem(e, "Atualização de Ferramentas");
                } finally {
                    JanelaLogin.connection.setAutoCommit(true);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Esta ferramenta já esta cadastrada.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
    }

    /**
     * Inicializando as configurações da tela
     *
     * @throws SQLException
     */
    private void configurarJanela() throws SQLException {
        LinkedList<SituacaoFerramenta> listaSituacao = EnumSituacaoFerramenta.ListaSituacao();
        for (int i = 0; i < listaSituacao.size(); i++) {
            jComboBox6.addItem(EnumSituacaoFerramenta.ConvertEnumString(listaSituacao.get(i)));
        }

        if (idFerramenta != 0) { // Edição de usuário
            carregarInformacoes();
        } else {
            this.configurarCamposObrigatorios();
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel3 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jButton6 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jLabel18 = new javax.swing.JLabel();
        jLabel19 = new javax.swing.JLabel();
        jLabel20 = new javax.swing.JLabel();
        jLabel21 = new javax.swing.JLabel();
        jLabel35 = new javax.swing.JLabel();
        jLabel42 = new javax.swing.JLabel();
        jTextField5 = new TextFieldValidator(10, 2, true, true, "text", jLabel18);
        jTextField12 = new TextFieldValidator(100, 3, true, true, "text", jLabel19);
        jFormattedTextField5 = new FormatedFieldValidator(true, true, "date", jLabel21);
        jTextField1 = new TextFieldValidator(100, 3, true, true, "text", jLabel42);
        jComboBox6 = new javax.swing.JComboBox();
        jFormattedTextField3 = new FormatedFieldValidator(true, true, "money", jLabel20);
        jLabel43 = new javax.swing.JLabel();
        jTextField2 = new TextFieldValidator(100, 3, true, true, "text", jLabel43);
        jLabel44 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jTextField6 = new TextFieldValidator(100, 5, true, true, "text", jLabel42);
        jLabel47 = new javax.swing.JLabel();
        jLabel48 = new javax.swing.JLabel();
        jTextField7 = new TextFieldValidator(40, 3, true, true, "text", jLabel48);
        jLabel7 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Ferramentas");
        setBackground(Configurations.getBackGroundColor());
        setMinimumSize(new java.awt.Dimension(620, 325));
        setPreferredSize(new java.awt.Dimension(663, 325));
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jPanel3.setBackground(Configurations.getBackGroundColor());
        jPanel3.setPreferredSize(new java.awt.Dimension(700, 300));
        jPanel3.setLayout(null);

        jPanel1.setBackground(Configurations.getBackGroundColor());
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel1.setLayout(null);

        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/cancel.png"))); // NOI18N
        jButton6.setText("Cancelar");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton6);
        jButton6.setBounds(140, 250, 100, 23);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/add.png"))); // NOI18N
        jButton1.setText("Cadastrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton1);
        jButton1.setBounds(20, 250, 100, 23);

        jLabel18.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel18.setText("Identificador");
        jPanel1.add(jLabel18);
        jLabel18.setBounds(20, 20, 80, 14);

        jLabel19.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel19.setText("Nome");
        jPanel1.add(jLabel19);
        jLabel19.setBounds(105, 20, 90, 14);

        jLabel20.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel20.setText("Valor");
        jPanel1.add(jLabel20);
        jLabel20.setBounds(435, 20, 29, 14);

        jLabel21.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel21.setText("Data de Compra");
        jPanel1.add(jLabel21);
        jLabel21.setBounds(530, 20, 120, 14);

        jLabel35.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel35.setText("Situação");
        jPanel1.add(jLabel35);
        jLabel35.setBounds(520, 70, 50, 14);

        jLabel42.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel42.setText("Fabricante");
        jPanel1.add(jLabel42);
        jLabel42.setBounds(20, 70, 80, 14);
        jPanel1.add(jTextField5);
        jTextField5.setBounds(20, 40, 80, 20);
        jPanel1.add(jTextField12);
        jTextField12.setBounds(105, 40, 325, 20);
        jPanel1.add(jFormattedTextField5);
        jFormattedTextField5.setBounds(530, 40, 100, 20);
        jPanel1.add(jTextField1);
        jTextField1.setBounds(20, 90, 180, 20);

        jPanel1.add(jComboBox6);
        jComboBox6.setBounds(520, 90, 110, 20);
        jPanel1.add(jFormattedTextField3);
        jFormattedTextField3.setBounds(435, 40, 90, 20);

        jLabel43.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel43.setText("Modelo");
        jPanel1.add(jLabel43);
        jLabel43.setBounds(205, 70, 80, 14);
        jPanel1.add(jTextField2);
        jTextField2.setBounds(205, 90, 180, 20);

        jLabel44.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel44.setText("Descrição");
        jPanel1.add(jLabel44);
        jLabel44.setBounds(20, 120, 80, 14);

        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("Monospaced", 1, 10)); // NOI18N
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(2);
        jTextArea1.setWrapStyleWord(true);
        jScrollPane1.setViewportView(jTextArea1);
        jTextArea1.setDocument(new FixedLengthDocument(200));

        jPanel1.add(jScrollPane1);
        jScrollPane1.setBounds(20, 140, 610, 50);

        jTextField6.setDisabledTextColor(new java.awt.Color(0, 0, 0));
        jTextField6.setEnabled(false);
        jPanel1.add(jTextField6);
        jTextField6.setBounds(20, 220, 310, 20);

        jLabel47.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel47.setText("Funcionário ");
        jPanel1.add(jLabel47);
        jLabel47.setBounds(20, 200, 80, 14);

        jLabel48.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel48.setText("Localização");
        jPanel1.add(jLabel48);
        jLabel48.setBounds(390, 70, 80, 14);
        jPanel1.add(jTextField7);
        jTextField7.setBounds(390, 90, 125, 20);

        jLabel7.setText("M - MANUAL");
        jPanel1.add(jLabel7);
        jLabel7.setBounds(340, 220, 70, 14);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("XAAAA :");
        jPanel1.add(jLabel1);
        jLabel1.setBounds(350, 200, 60, 14);

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel5.setText("X -");
        jPanel1.add(jLabel5);
        jLabel5.setBounds(410, 200, 30, 14);

        jLabel10.setText("GRUPOS");
        jPanel1.add(jLabel10);
        jLabel10.setBounds(440, 200, 50, 14);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setText("AAAA -");
        jPanel1.add(jLabel3);
        jLabel3.setBounds(490, 200, 40, 14);

        jLabel2.setText("CÓD. FERRAMETA");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(540, 200, 100, 14);

        jLabel9.setText("C - COMBUSTÃO");
        jPanel1.add(jLabel9);
        jLabel9.setBounds(440, 220, 80, 14);

        jLabel4.setText("E - ELÉTRICA");
        jPanel1.add(jLabel4);
        jLabel4.setBounds(340, 240, 90, 14);

        jLabel6.setText("V - VIATURA");
        jPanel1.add(jLabel6);
        jLabel6.setBounds(440, 240, 80, 14);

        jPanel3.add(jPanel1);
        jPanel1.setBounds(0, 0, 660, 280);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 663, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)
                .addGap(2, 2, 2))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        WindowsFunctions.resizePanel(jPanel3, jPanel1);
    }//GEN-LAST:event_formComponentResized

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        LinkedList<String> fieldValidadeList = validarCampos();
        if (fieldValidadeList.size() == 0) {
            if (idFerramenta == 0) {
                adicionarFerramenta();
            } else {
                editarFerramenta();
            }
        } else {
            JOptionPane.showMessageDialog(null, ValidationFunctions.getValidationMessage(fieldValidadeList), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton6ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton6;
    private javax.swing.JComboBox jComboBox6;
    private javax.swing.JFormattedTextField jFormattedTextField3;
    private javax.swing.JFormattedTextField jFormattedTextField5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel35;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel42;
    private javax.swing.JLabel jLabel43;
    private javax.swing.JLabel jLabel44;
    private javax.swing.JLabel jLabel47;
    private javax.swing.JLabel jLabel48;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField12;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    private javax.swing.JTextField jTextField7;
    // End of variables declaration//GEN-END:variables
}
